package store.lunangangster.engine.impl.util;

import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import store.lunangangster.bpmn.model.definition.TimerEventDefinition;
import store.lunangangster.engine.NodeFlowException;
import store.lunangangster.engine.impl.Context;
import store.lunangangster.engine.impl.calendar.CycleCalendar;
import store.lunangangster.engine.impl.calendar.DefaultCalendarManager;
import store.lunangangster.engine.impl.calendar.DurationCalendar;

public class CalendarUtil {

  public static Date resolveDateFromTimerEventDefinition(TimerEventDefinition timerEventDefinition) {
    String calendarType;
    String dateString;
    Date dueDate;
    if (StringUtils.isNotBlank(timerEventDefinition.getTimeDate())) {
      calendarType = DurationCalendar.name;
      dateString = timerEventDefinition.getTimeDate();
    } else if (StringUtils.isNotBlank(timerEventDefinition.getTimeDuration())) {
      calendarType = DurationCalendar.name;
      dateString = timerEventDefinition.getTimeDuration();
    } else if (StringUtils.isNotBlank(timerEventDefinition.getTimeCycle())) {
      calendarType = CycleCalendar.name;
      dateString = timerEventDefinition.getTimeCycle();
    } else {
      throw new NodeFlowException("错误的TimerEventDefinition：未定义timeDate或timeDuration或timeCycle");
    }

    DefaultCalendarManager calendarManager = Context.getProcessEngineConfiguration()
        .getCalendarManager();
    return calendarManager.resolveDueDate(calendarType, dateString);
  }


}
